package com.funmi.lizip.security.service;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

@Slf4j
@Component("pms")
public class PermissionService {

	/**
	 * 判断接口是否有xxx:xxx权限
	 * @param permission 权限
	 * @return {boolean}
	 */
	public boolean hasPermission(String permission) {
		// 判断是否有权限配置
		if (StrUtil.isBlank(permission)) {
			return false;
		}

		// 获取用户的认证对象
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return false;
		}

		// 获取用户分配的角色和权限
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

		// 判断权限
		return authorities.stream()
				// GrantedAuthority -> String
				//.map((authority) -> authority.getAuthority())
				.map(GrantedAuthority::getAuthority)
				// 过滤所有值为空的权限字符串
				//.filter((s) -> StringUtils.hasText(s))
				.filter(StringUtils::hasText)
				// 权限判断，PatternMatchUtils.simpleMatch是用正则表达式规则来匹配，更加灵活
				//.anyMatch(x -> permission.equals(x))
				.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
	}

}